package com.live.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;








import com.live.model.Admin;
import com.live.model.Apply;
import com.live.service.AdminService;
import com.live.service.ApplyService;
import com.live.util.StringUtil;


@WebServlet("/apply")
public class ApplyController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private ApplyService applyService = null;
	private AdminService adminService =null;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String companyName = request.getParameter("companyName").trim();
		String userName = request.getParameter("userName").trim();
		String userPhone = request.getParameter("userPhone").trim();
		String userEmail = request.getParameter("userEmail").trim();
		String message = request.getParameter("message").trim();
		String code = request.getParameter("code").trim();
		HttpSession session = request.getSession(true);
		String sessionCode = (String)session.getAttribute(CodeController.IMG_CODE);
		String errInfo = "";
		if (null == code || "".equals(code)) {
			errInfo = "nullcode"; // 验证码为空
		} else {
			if (sessionCode.equalsIgnoreCase(code)) {
				errInfo = "success";
			} else {
				errInfo = "codeerror"; // 验证码输入有误
			}
		}
		if (errInfo.equals("success")) {
				adminService = new AdminService();
				Apply apply = new Apply();
				apply.setCompanyName(companyName);
				apply.setUserName(userName);
				apply.setUserPhone(userPhone);
				apply.setUserEmail(userEmail);
				apply.setMessage(message);
				apply.setStart(1);
				List<Admin> list = adminService.getAdminId();
				Admin admin= new Admin();		
					if( 0==list.size()){
						adminService.editAdminSign(admin);
						List<Admin> list1 = adminService.getAdminId();
						apply.setAdminId(list1.get(0).getId());
						admin.setId(list1.get(0).getId());
						admin.setSign(1);
						int rel =	adminService.editAdmin(admin);
					}else {
						apply.setAdminId(list.get(0).getId());
						admin.setId(list.get(0).getId());
						admin.setSign(1);
						int rel =	adminService.editAdmin(admin);
					}
				apply.setTime(StringUtil.getStrDateTime());
				applyService = new ApplyService();
				int rel = applyService.addApply(apply);
				
		} 
		String strRel = errInfo;
		response.getOutputStream().write(strRel.getBytes());
	}
	
	
	
}


